package com.example.wechatscancode;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.wechatscancode.utils.Constant;
import com.example.wechatscancode.utils.EncryptUtils;
import com.example.wechatscancode.utils.HttpsUtils;
import com.tencent.mm.opensdk.diffdev.DiffDevOAuthFactory;
import com.tencent.mm.opensdk.diffdev.IDiffDevOAuth;
import com.tencent.mm.opensdk.diffdev.OAuthErrCode;
import com.tencent.mm.opensdk.diffdev.OAuthListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Random;

public class MainActivity extends AppCompatActivity {
    public final static String TAG = "MainActivity";
    private ImageView IvWeChat;
    private ImageView IvSmdl;
    IDiffDevOAuth oauth;
    String noncestr;
    String timeStamp;
    String sha;
    Toast mToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        oauth = DiffDevOAuthFactory.getDiffDevOAuth();
        IvWeChat = (ImageView) findViewById(R.id.iv_wxm);

        ConnectWechat();
    }

    OAuthListener mOAuthListener = new OAuthListener() {
        @Override
        public void onAuthGotQrcode(String s, byte[] bytes) {
            Log.e(TAG, "onAuthGotQrcode: ");
            IvWeChat.setImageBitmap(null);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, new BitmapFactory.Options());
            IvWeChat.setImageBitmap(bitmap);
        }

        @Override
        public void onQrcodeScanned() {

        }

        @Override
        public void onAuthFinish(OAuthErrCode oAuthErrCode, String s) {
            Log.e(TAG, "onAuthFinish: ");
            if (oAuthErrCode == OAuthErrCode.WechatAuth_Err_OK) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constant.WECHAT_APPID + "&secret=" + Constant.WECHAT_SECRET + "&code=" + s + "&grant_type=authorization_code";
                            Log.e(TAG, "onAuthFinish: url: " + url);
                            String res = HttpsUtils.submitGetData(url, null);
                            Log.e(TAG, "服务器返回: " + res);
                            JSONObject jsonObject = new JSONObject(res);
                            String openid = jsonObject.getString("openid");
                            String access_token = jsonObject.getString("access_token");

                            url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid;
                            res = HttpsUtils.submitGetData(url, null);
                            Log.e(TAG, "服务器返回: " + res);
                            jsonObject = new JSONObject(res);
                            String unionid = jsonObject.getString("unionid");
                            openid = jsonObject.getString("openid");
                            String nickName = jsonObject.getString("nickname");
                            int sex = jsonObject.getInt("sex");
                            String headimgurl = jsonObject.getString("headimgurl");
                            String language = jsonObject.getString("language");
                            String city = jsonObject.getString("city");
                            String province = jsonObject.getString("province");
                            String country = jsonObject.getString("country");
                            JSONArray privilege = jsonObject.getJSONArray("privilege");
                            Log.e(TAG, "unionid: " + unionid);
                            Log.e(TAG, "openid: " + openid);
                            Log.e(TAG, "nickName: " + nickName);
                            Log.e(TAG, "sex: " + sex);
                            Log.e(TAG, "headimgurl: " + headimgurl);
                            Log.e(TAG, "language: " + language);
                            Log.e(TAG, "city: " + city);
                            Log.e(TAG, "province: " + province);
                            Log.e(TAG, "country: " + country);
                            Log.e(TAG, "privilege: " + privilege);


                            //String转换成Base64
                            //GlobalObjects.bitmap = Base64Utils.decodeImage();

//                            GlobalObjects.bitmap = BitmapUtils.returnBitMap(headimgurl);
//
//                            GlobalObjects.resident_info.NAME = nickName;
//                            GlobalObjects.resident_info.RESIDENT_ID = openid;
//                            BleLog.e(TAG, GlobalObjects.bitmap + "头像图片");


                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    // Intent intent = new Intent(Wechat_Login.this, ButtonMainActivity.class);
                                    // intent.putExtra("nickname", nickName);
                                    //  startActivity(intent);
                                    // startActivity(new Intent(Wechat_Login.this, ButtonMainActivity.class));
                                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

                                }
                            });

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
            } else if (oAuthErrCode == OAuthErrCode.WechatAuth_Err_Timeout) {
                showTip("二维码已过期，请点击刷新");
                Log.e(TAG, "二维码已过期，下面重新刷新UI，再次执行一遍就ok了");
            } else if (oAuthErrCode == OAuthErrCode.WechatAuth_Err_Cancel) {
                showTip("没有授权返回在刷新一下二维码");
                Log.e(TAG, "没有授权返回在刷新一下二维码");
            } else if (oAuthErrCode == OAuthErrCode.WechatAuth_Err_NetworkErr) {
                showTip("网络错误");
                Log.e(TAG, "网络错误");
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //二维码登录
        oauth.removeAllListeners();
        oauth.stopAuth();
    }

    /**
     * 获取access_token
     *
     * @param
     */
    //第一步
    private void ConnectWechat() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constant.WECHAT_APPID + "&secret=" + Constant.WECHAT_SECRET;
                    Log.e(TAG, "url_1: " + url);
                    String res = HttpsUtils.submitGetData(url, null);
                    Log.e(TAG, "服务器返回: " + res);

                    //获取access_token
                    String access_token = new JSONObject(res).getString("access_token");
//                    url = MyApiUtil.WeChatLoginSecond + "access_token=" + access_token + "&type=2";
                    url = "https:api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=2";
                    Log.e(TAG, "url_2: " + url);

                    res = HttpsUtils.submitGetData(url, null);

                    Log.e(TAG, "服务器返回: " + res);
                    String ticket = new JSONObject(res).getString("ticket");

                    StringBuilder str = new StringBuilder();// 定义变长字符串
                    // 随机生成数字，并添加到字符串
                    for (int i = 0; i < 8; i++) {
                        str.append(new Random().nextInt(10));
                    }
                    noncestr = str.toString();
                    timeStamp = Long.toString(System.currentTimeMillis()).substring(0, 10);
                    String string1 = String.format("appid=%s&noncestr=%s&sdk_ticket=%s&timestamp=%s", Constant.WECHAT_APPID, noncestr, ticket, timeStamp);
                    sha = EncryptUtils.getSHA(string1);
                    Log.e(TAG, "二维码验证方式" + sha);
                    oauth.auth(Constant.WECHAT_APPID, "snsapi_userinfo", noncestr, timeStamp, sha, mOAuthListener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    //显示提示
    public void showTip(final String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mToast == null) {
                    mToast = Toast.makeText(getApplicationContext(), "",
                            Toast.LENGTH_SHORT);
                    LinearLayout layout = (LinearLayout) mToast.getView();    //显示视图
                    TextView tv = (TextView) layout.getChildAt(0);
                    tv.setTextSize(30);
                }
//                mToast.cancel();
//                mToast.setGravity(Gravity.CENTER, 100, 0);
                mToast.setText(str);
                mToast.show();
            }
        });
    }

    public void showMSG(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //   MApplication.getInstance().showMSG(msg);
            }
        });
    }
}